//
//  NSString+URLEncode.m
//  CoolFM
//
//  Created by dllo on 16/9/3.
//  Copyright © 2016年 DM.C All rights reserved.
//

#import "NSString+URLEncode.h"

@implementation NSString (URLEncode)

//data转换为十六进制的。
+ (NSString *)hexStringFromData:(NSData *)myD {
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];//16进制数
        if([newHexStr length] == 1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%%%@",hexStr,newHexStr];
    }
    return hexStr;
}

- (NSString *)URLEncodeString {
    NSMutableString *chineseString = [[NSMutableString alloc] init];
    for (int i=0; i<[self length]; i++)
    {
        int a = [self characterAtIndex:i];
        // 是汉字
        if (a < 0x9fff && a > 0x4e00) {
            NSData *data = [[self substringWithRange:NSMakeRange(i, 1)] dataUsingEncoding:NSUTF8StringEncoding];
            [chineseString appendString:[NSString hexStringFromData:data].uppercaseString];
        } else {
            [chineseString appendString:[self substringWithRange:NSMakeRange(i, 1)]];
        }
    }
    return chineseString;
}



@end
